<template>
  <view class="xuanshang-container">
    <myHeader title="悬赏求助" showBack />
    <view class="xuanshang-content">
      <div class="input-container">
        <u-form :model="formModel" labelPosition="left" labelWidth="180rpx"
          :labelStyle="{ 'fontWeight': 'bold', 'font-size': '30rpx', }" ref="uForm">
          <u-form-item label="主题" prop="title" borderBottom>
            <u-input input-align="right" v-model="formModel.title" placeholder="目前您遇到什么问题" border="none"></u-input>
          </u-form-item>
          <u-form-item label="详细描述" prop="description" borderBottom>
            <u-input input-align="right" v-model="formModel.description" placeholder="详细说明问题" border="none"></u-input>
          </u-form-item>
          <u-form-item label="病例报告" prop="imageUrl" borderBottom labelPosition="top">
            <u-upload :fileList="formModel.imageUrl" width="200" height="200" @afterRead="uploadImage"
              @delete="deletePic" name="fileUpload" multiple :maxCount="10" :previewFullImage="true"></u-upload>
          </u-form-item>
          <u-form-item label="调查问卷" prop="name" borderBottom labelPosition="top">
            <u-button @click="goSuvery" type="primary" :custom-style="{ marginTop: '20rpx' }" shape="circle"
              size="large">{{ isSuv ? '已填写' : '点击填写' }}</u-button>
          </u-form-item>
          <view style="margin-top: 20rpx; font-weight: bold; color: 36rpx;">基本信息</view>
          <u-form-item label="性别" prop="sex" borderBottom>
            <u-radio-group v-model="formModel.sex" size="32rpx" placement="row">
              <u-radio label-size="32rpx" icon-size="32rpx" :customStyle="{ marginBottom: '8px' }"
                v-for="(item, index) in sexList" :key="index" :label="item.name" :name="item.value">
              </u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item label="身高:" prop="height" borderBottom>
            <u-input input-align="right" type="number" v-model="formModel.height" placeholder="请输入" border="none">
              <template slot="suffix">
                <text>cm</text>
              </template></u-input>
          </u-form-item>
          <u-form-item label="体重:" prop="weight" borderBottom>
            <u-input input-align="right" type="number" v-model="formModel.weight" placeholder="请输入" border="none">
              <template slot="suffix">
                <text>kg</text>
              </template></u-input>
          </u-form-item>
          <u-form-item label="出生日期:" prop="birthday" borderBottom>
            <u-input input-align="right" placeholder="请选择" v-model="formModel.birthday"
              @click.native="showBirthday = true" readonly border="none"></u-input>
            <u-datetime-picker immediateChange @confirm="bConfirm" @change="bChange" @cancel="showBirthday = false"
              :show="showBirthday" mode="date"></u-datetime-picker>
          </u-form-item>
          <u-form-item label="所在城市:" prop="detailAddress" borderBottom>
            <!-- <u-input input-align="right" v-model="formModel.detailAddress" border="none"></u-input> -->
            <uni-data-picker :clear-icon="false" :localdata="areaTree" popup-title="请选择" @change="onchange"
              :map="{ text: 'name', value: 'id' }">
            </uni-data-picker>
          </u-form-item>
          <u-form-item label="预期接单" prop="expectedDate" borderBottom>
            <u-input input-align="right" placeholder="请选择" v-model="formModel.expectedDate"
              @click.native="showExpectedDate = true" readonly border="none"></u-input>
            <u-datetime-picker immediateChange @confirm="eConfirm" @cancel="showExpectedDate = false"
              :show="showExpectedDate" mode="date"></u-datetime-picker>
          </u-form-item>
          <u-form-item label="悬赏金额" prop="reward" borderBottom>
            <u-input input-align="right" type="number" placeholder="请输入" v-model="formModel.reward" border="none">
              <template slot="suffix">
                <text>元</text>
              </template>
            </u-input>
          </u-form-item>
          <u-form-item label="任务小费" prop="tip" borderBottom>
            <u-input input-align="right" type="number" v-model="formModel.tip" placeholder="请输入" border="none">
              <template slot="suffix">
                <text>元</text>
              </template></u-input>
          </u-form-item>
        </u-form>
        <u-checkbox-group v-model="urgent" size="32rpx" placement="column" @change="groupChange">
          <u-checkbox shape="square" label-size="32rpx" icon-size="32rpx" :customStyle="{ margin: '20rpx 0' }"
            label="urgent" name="urgent">
            <text>加急《额外支付¥{{ configData.chargeTaskUrgent / 100 }}》</text>
          </u-checkbox>
        </u-checkbox-group>
        <view style="margin: 20rpx 0;">
          <u-button @click="hanadleDone" type="primary">支付¥{{ allPrice }}定金并发布(合计悬赏金¥{{ finallyPrice }})</u-button>
        </view>
        <!-- <u-checkbox-group v-model="tongyi" size="32rpx" placement="column" @change="groupChange2">
          <u-checkbox shape="square" label-size="32rpx" icon-size="32rpx" :customStyle="{ marginBottom: '20rpx' }"
            label="tongyi" name="tongyi">
            <text>支付即表示,您同意xxx的《支付协议》</text>
          </u-checkbox>
        </u-checkbox-group> -->
      </div>
      <view class="custom-dialog" v-if="showApplyPromoterDialog">
        <view class="dialog-mask" @tap="closeDialog"></view>
        <view class="dialog-content">
          <image class="dialog-img" src="https://www.rebirthealth.com/static/images/tuiguang.jpg"></image>
          <view class="dialog-tip">支付{{ (bizConfig.pledgeAmountSpreader || 0) / 100 }}元申请成为推广者用户</view>
          <view class="agreement">
            <checkbox-group @change="onExpertAgreeChange">
              <label class="agreement-label">
                <checkbox value="agree" :checked="isAgreeExpert" color="#2F7FB9" />
                <text class="agreement-text">我已阅读并同意</text>
                <text class="agreement-link" @click.stop="navigateTo('/pages/my/settings/protocol')">《支付协议》</text>
              </label>
            </checkbox-group>
          </view>
          <button class="confirm-btn" :disabled="!isAgreeExpert" @click="handleExpertApply">去支付</button>
        </view>
      </view>
    </view>
  </view>

</template>

<script>
import myHeader from "@/component/header";
import { getBizConfig, createMission, prepay } from "../../api";
export default {
  components: {
    myHeader
  },
  data() {
    return {
      formModel: {
        title: "",
        description: "",
        imageUrl: [],
        sex: null,
        height: "",
        weight: "",
        birthday: "",
        detailAddress: '',
        expectedDate: "",
        reward: '',
        tip: '',
      },
      // 测试数据
      // formModel: {
      //   title: "测试",
      //   description: "测试2",
      //   imageUrl: [{ url: 'https://www.rebirthealth.com/admin-api/infra/file/4/get/0b6c73943d8bac8237a8157df2ea4f2b7fd16834175f7b019419896bb946831f.png' }],
      //   sex: 1,
      //   height: "180",
      //   weight: "75",
      //   birthday: "2025-05-05",
      //   detailAddress: 140406,
      //   expectedDate: "2025-05-05",
      //   reward: 10,
      //   tip: 10,
      // },

      urgent: '',
      tongyi: '',
      showExpectedDate: false,
      showBirthday: false,
      fomeRules: {
        title: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        imageUrl: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              return !!value.length
            },
          }
        ],
        sex: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              return [0, 1, 2].includes(value)
            },
          }
        ],
        height: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        weight: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        birthday: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        detailAddress: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              return !!value
            },
          }
        ],
        expectedDate: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        reward: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              return !!value
            },
          }
        ],
      },
      userInfo: {},
      sexList: [
        {
          name: '男',
          value: 1
        },
        {
          name: '女',
          value: 2
        },
        {
          name: '其他',
          value: 0
        },
      ],
      configData: {},
      suveryList: [],
      isSuv: false,
      isAgreeExpert: false,
      showApplyPromoterDialog: false
    };
  },
  computed: {
    areaTree() {
      return uni.getStorageSync("areaTree")
    },
    allPrice() {
      let price =
        (Number(this.formModel.reward) *
          this.configData.paymentRatioTaskPublish) /
        100;
      if (this.formModel.tip) {
        price += Number(this.formModel.tip);
      }
      if (this.urgent[0]) {
        price += Number(this.configData.chargeTaskUrgent / 100);
      }
      return price;
    },
    finallyPrice() {
      let price = Number(this.formModel.reward);
      if (this.formModel.tip) {
        price += Number(this.formModel.tip);
      }
      if (this.urgent[0]) {
        price += Number(this.configData.chargeTaskUrgent / 100);
      }
      return price;
    },
  },
  onShow() {
    this.userInfo = uni.getStorageSync("userInfo");
  },
  onLoad(options) {
    this.formModel.title = options.title
    this.getBizConfig()

  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.fomeRules)
  },
  methods: {
    goSuvery() {
      uni.navigateTo({
        url: '/pages/reward/suveryList',
        events: {
          success: (data) => {
            console.log(data)
            this.suveryList = data
            this.isSuv = true
          },
        },
        fail: (err) => {
          console.log(err)
        }
      })
    },
    async getBizConfig() {
      let res = await getBizConfig();
      this.configData = res || {}
    },
    onchange(e) {
      const arr = e.detail.value
      this.formModel.detailAddress = arr[arr.length - 1].value
    },
    onExpertAgreeChange(e) {
      this.isAgreeExpert = e.detail.value.includes('agree');
    },
    // 关闭弹窗
    closeDialog() {
      this.showApplyPromoterDialog = false;
      // 重置勾选状态
      this.isAgreeExpert = false;
    },
    async handleExpertApply() {
      if (!this.isAgreeExpert) {
        return uni.$u.toast('请阅读协议并勾选同意')
      }
      let suveryList = []
      for (
        let index = 0;
        index < this.suveryList.length;
        index++
      ) {
        const { pitch, title, type, value } =
          this.suveryList[index];
        const submitSurvey = { pitch, title, type, value };
        if (submitSurvey.type == 3) {
          submitSurvey.pitch = submitSurvey.pitch.join();
        }
        suveryList.push(submitSurvey);
      }
      let params = JSON.parse(JSON.stringify(this.formModel));
      params.survey = suveryList;
      params.imageUrl = params.imageUrl.map((c) => c.url);
      params.status = "0";
      params.reward = params.reward * 100;
      params.tip = params.tip * 100;
      if (params.urgent) {
        params.fee = this.configData.chargeTaskUrgent;
      } else {
        params.fee = 0;
      }
      let orderId = await createMission(params)
      // 3. 调起微信支付（使用箭头函数保持 this 指向）
      const payConfig = await prepay(orderId);
      if (!payConfig) {
        uni.showToast({
          title: '支付订单创建失败',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 4. 执行微信支付
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: payConfig.timeStamp,
        nonceStr: payConfig.nonceStr,
        package: payConfig.packageValue,
        signType: payConfig.signType,
        paySign: payConfig.paySign,
        success: (res) => {
          console.log('支付成功，响应：', res); // 添加日志确认是否执行
          // 支付成功：关闭弹出层 + 刷新数据
          // this.getDetail(); // 仅在成功时刷新
          uni.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          });
          setTimeout(() => {
            uni.navigateTo('/pages/my/myOrders')
          }, 1000);
        },
        fail: (err) => {
          // 支付失败/取消：显示提示，不刷新数据
          const errMsg = err.errMsg || '支付失败';
          if (errMsg.includes('cancel')) {
            uni.showToast({
              title: '支付已取消',
              icon: 'none',
              duration: 1500
            });
          } else {
            uni.showToast({
              title: `支付失败：${errMsg}`,
              icon: 'none',
              duration: 2000
            });
          }
        },
      });
    },
    hanadleDone() {
      // let valid = await this.$refs.uForm.validate()
      // console.log(valid)
      if (!this.isSuv) {
        return uni.$u.toast('请填写调查问卷')
      }
      this.$refs.uForm.validate().then(async () => {
        // uni.$u.toast('校验通过')
        this.showApplyPromoterDialog = true
      }).catch(errors => {
        console.log(errors)
      })
    },
    bConfirm({ value }) {
      this.formModel.birthday = uni.$u.timeFormat(new Date(value), 'yyyy-mm-dd')
      this.showBirthday = false
    },
    eConfirm({ value }) {
      this.formModel.expectedDate = uni.$u.timeFormat(new Date(value), 'yyyy-mm-dd')
      this.showExpectedDate = false
    },
    deletePic(event) {
      this.formModel.imageUrl.splice(event.index, 1);
    },
    async uploadImage(event) {
      let lists = [].concat(event.file);
      let fileListLen = this.formModel.imageUrl.length;
      lists.map((item) => {
        this.formModel.imageUrl.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this.formModel.imageUrl[fileListLen];
        this.formModel.imageUrl.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    async uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: "https://www.rebirthealth.com/app-api/infra/file/upload", // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          formData: {
            user: "test",
          },
          success: (res) => {
            setTimeout(() => {
              let data = JSON.parse(res.data);
              resolve(data.data);
            }, 1000);
          },
        });
      });
    },
  }
}
</script>

<style lang="less" scoped>
.xuanshang-content {
  background-color: #141a2e;
  padding: 32rpx;
  padding-bottom: 180rpx;

  .input-container {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 32rpx 32rpx;
  }

  /deep/ .u-form-item__body {
    padding: 32rpx 0;
  }

  /deep/ .u-radio-group {
    justify-content: space-between;
  }

  /deep/ .input-value-border {
    border: none;

    .selected-list,
    .selected-area {
      justify-content: flex-end;
    }

    .selected-area {
      color: #c0c4cc;
      font-size: 28rpx;
    }
  }

  // 自定义弹窗样式
  .custom-dialog {
    .dialog-mask {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
    }

    .dialog-content {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 600rpx;
      background: #fff;
      border-radius: 16rpx;
      padding: 40rpx;
      z-index: 1000;

      /* 添加以下代码实现弹窗高度占满屏幕80%并添加滚动条 */
      height: 80vh;
      /* 设置高度为视口高度的80% */
      max-height: 80vh;
      overflow-y: auto;
      /* 添加垂直滚动条 */

      .dialog-img {
        width: 100%;
        height: 2568rpx;
        border-radius: 8rpx;
        margin-bottom: 30rpx;
      }

      .dialog-tip {
        font-size: 32rpx;
        color: #333;
        text-align: center;
        margin-bottom: 40rpx;
        font-weight: bold;
      }

      .agreement {
        margin-bottom: 40rpx;

        .agreement-label {
          display: flex;
          align-items: center;
          font-size: 24rpx;
          color: #666;

          .agreement-text {
            margin: 0 8rpx;
          }

          .agreement-link {
            color: #2F7FB9;
            text-decoration: underline;
          }
        }
      }

      .confirm-btn {
        width: 100%;
        height: 80rpx;
        line-height: 80rpx;
        background: linear-gradient(90deg, #2F7FB9 0%, #045FB2 100%);
        color: #fff;
        font-size: 32rpx;
        border-radius: 8rpx;
        border: none;

        &[disabled] {
          background: #ccc;
          color: #999;
        }
      }
    }
  }
}
</style>